package com.zyh.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyh.entity.Auction;
import com.zyh.service.IAuctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhang
 * @since 2022-04-26
 */
@RestController
@RequestMapping("/auction")
public class AuctionController {
    @Autowired
    IAuctionService service;
    @Value("${imgPath}")
    private String imgPath;

    @GetMapping("/selectAll")
    public List<Auction> selectAll(){
        List<Auction> list = service.list();
        return list;
    }

    @GetMapping("/selectByPage")
    public IPage<Auction> selectByPage(@RequestBody Page page,Auction auction){
        //把auction里面的搜索条件转换为queryWrapper
        QueryWrapper<Auction> wrapper=new QueryWrapper<>();
        if(auction!=null){
            if(auction.getAuctionName()!=null&&!"".equals(auction.getAuctionName())){
                wrapper.like("auctionName",auction.getAuctionName());
            }
            if(auction.getAuctionDesc()!=null&&!"".equals(auction.getAuctionDesc())){
                wrapper.like("auctionDesc",auction.getAuctionDesc());
            }
            if(auction.getAuctionDesc()!=null&&!"".equals(auction.getAuctionDesc())){
                wrapper.like("auctionDesc",auction.getAuctionDesc());
            }
//            if(auction.getAuctionStartTime()!=null){
//                wrapper.eq("auctionStartTime",auction.getAuctionStartTime());
//            }
            if(auction.getAuctionStartPrice()!=null){
                wrapper.eq("auctionStartPrice",auction.getAuctionStartPrice());
            }
        }

        return service.page(page,wrapper);
    }

    @DeleteMapping("/admin/delete/{id}")
    public void deleteById(@PathVariable("id")int id){
        service.removeById(id);
    }
    @GetMapping("/selectOne/{id}")
    public Auction selectOne(@PathVariable("id") int id){
        return service.getById(id);
    }

    @PostMapping("/admin/upload")
    public String upload(MultipartFile file) throws Exception{
        String uuid = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        File targetFile = new File(imgPath, uuid + originalFilename);
        //把file这个文件复制到另一个文件路径里面
        file.transferTo(targetFile);
        return  uuid+originalFilename;
    }

    @PostMapping("/admin/add")
    public void add(@RequestBody Auction auction){
        service.save(auction);
    }
}

